﻿using System;
using System.Globalization;
using Finance.Controllers;
using Finance.Data.Entities;

namespace Finance.ViewModels
{
	internal class DebtDocumentViewModel : DocumentViewModelBase
	{
		public string PercentRate { get; set; }

		IDebtDocument DebtDocument { get { return (IDebtDocument)Document; } }

		public DebtDocumentViewModel(IDebtDocument document, IDocumentBaseController controller) 
			: base(document, controller)
		{
			PercentRate = (document.Rate * 100m).ToString("#.###", CultureInfo.InvariantCulture);
		}

		public override void ApplyChangesToModel()
		{
			base.ApplyChangesToModel();

			try
			{
				var invariantRate = PercentRate.Replace(".", CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator)
				                               .Replace(",", CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
				DebtDocument.Rate = decimal.Parse(invariantRate) / 100.0m;
			}
			catch(FormatException)
			{
				DebtDocument.Rate = 0;
			}
		}
	}
}
